const fs   = require('fs');
const path = require('path');
const DIR  = `${path.dirname(__dirname)}/runtime/log/`;
const { env } = process;
/**
 * 获取时间
 */
function localDate(){
    const date = new Date(),
        year   = date.getFullYear(),
        month  = date.getMonth() + 1,
        day    = date.getDate();

    return `${year}-${month}-${day}`;
}

/**
 * 执行写入
 * @param {*} file 
 * @param {*} content 
 */
function _appendFiele(file,content){
    let isExists = fs.existsSync(DIR);
    if(!isExists){
        fs.mkdirSync(DIR);
    }
    fs.appendFile(file,content,function(err){
        if(err){
            console.log(err);
        }
    });
}

/**
 * 转换日志等级
 * @param {*} level 
 */
function _logLevel(level){
    const levelMap = {
        info: 3,
        warning: 2,
        danger: 1,
        log: 0
    };

    return isNaN(+level) ? levelMap[level]:+level;
}

/**
 * 日志记录
 * @param {*} content 
 * @param {*} file 
 */
function writeLog(content,file='_log',level = 'danger'){
    if(env.DEBUG === '1' || _logLevel(level) >= _logLevel(env.LOG_LEVEL)){
        if(content){
            const fileName = `${DIR}${localDate()}${file}.log`;
            _appendFiele(fileName,`\n${content}  ${new Date()}`);
        }
    }
}

module.exports = writeLog;